home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Chip 2005 June
/
ccd0605.iso
/
Software
/
Shareware
/
Programare
/
nativej
/
nativej-trial.exe
/
{app}
/
examples-source
/
Service.java
< prev
next >
Wrap
Text File
|
2004-12-14
|
2KB
|
68 lines
package examples;
import java.io.*;
import java.util.*;
/**
* This is a sample Java program that runs as a service.
*
* It appends the current date/time to a file called "service.log" at 5 secs interval
* until it is stopped.
*
* The "stop" command only works when used with NativeJ-generated executables.
* That's because NativeJ will create a separate thread within the same JVM space
* which will called main() with the "stop" parameter. It does not work when executed
* from the command line, since that will cause it to execute in separate JVM space.
*
* Take a look at Service2.java to find out how to implement the "stop" command that
* will work with BOTH the command line and NativeJ-generated executables.
*/
public class Service
{
/**
* The main() function accepts one single parameter: "start" or "stop".
* The first parameter starts the date/time logging service, while the
* second parameter stops the service.
*/
static boolean stop = false;
public static void main(String[] args) throws Exception
{
// Start the service
if (args[0].equals("-start"))
{
while(true)
{
// Append current date/time to log file
log("Current date/time is " + new Date());
// Sleep for 5 secs
Thread.currentThread().sleep(5000);
// Check for termination
if (stop)
{
log("Service stopped.");
break;
}
}
}
else
// Stop the service
if (args[0].equals("-stop"))
{
// Set the termination flag
stop = true;
}
}
/**
* Log given string to file "service.log".
*/
static void log(String msg) throws IOException
{
PrintWriter pw = new PrintWriter(new FileWriter("service.log", true));
pw.println(msg);
pw.close();
}
}